package com.lhy.tool.patchplugin.strategy;

import com.lhy.tool.patchplugin.model.CompileFileWrapper;
import com.lhy.tool.patchplugin.model.SrcFileWrapper;
import com.lhy.tool.patchplugin.model.TargetFileWrapper;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 依赖jar包策略类
 */
@Slf4j
public class JarStrategyImpl extends AbstractJavaFileStrategyImpl {

    private String targetFileSuffix;

    private static final String TARGET_FILE_DEFAULT_SUFFIX = ".jar";

    public JarStrategyImpl(String modulePath, List<String> targetWarModulePaths) {
        super(modulePath, targetWarModulePaths);
    }
    
    @PostConstruct
    protected void init() {
        int i = modulePath.substring(0, modulePath.length() - 1).lastIndexOf("/");
        this.moduleName = modulePath.substring(i + 1).replace("/", "");
        this.targetFileSuffix = TARGET_FILE_DEFAULT_SUFFIX;
    }

    @Override
    public boolean accept(SrcFileWrapper srcFile) {
        return srcFile.getAbsolutePath().startsWith(patchPluginProperties.getSrcPath() + modulePath);
    }

    @Override
    public List<CompileFileWrapper> getCompileFiles(SrcFileWrapper srcFileWrapper) {
        String versionFileName = getVersionFileName(moduleName + targetFileSuffix, patchPluginProperties.getVersion());
        File compileFile = new File(patchPluginProperties.getSrcPath() + modulePath + "/target/" + versionFileName);
        if (!compileFile.exists()) {
            compileFile = new File(patchPluginProperties.getSrcPath() + modulePath + "/target/" + moduleName + targetFileSuffix);
        }
        CompileFileWrapper fileWrapper = new CompileFileWrapper(compileFile);
        return Collections.singletonList(fileWrapper);
    }

    @Override
    public List<TargetFileWrapper> getTargetFiles(CompileFileWrapper compileFileWrapper) {
        List<TargetFileWrapper> targetFileWrappers = new ArrayList<>();
        targetWarModulePaths.forEach(targetWarModuleName -> {
            String targetVersionFileName = getVersionFileName(moduleName + targetFileSuffix, patchPluginProperties.getTargetVersion());
            File targetFile = new File(patchPluginProperties.getTargetPath() + targetWarModuleName + "/WEB-INF/lib/" + targetVersionFileName);
            targetFileWrappers.add(new TargetFileWrapper(targetFile));
        });
        return targetFileWrappers;
    }


    /**
     * @param oldJarName
     * @param version
     * @return java.lang.String
     * @throws 
     * @Title: getVersionFileName
     * @Description:  
     * @date 2018/4/23 10:12
     */   
    private String getVersionFileName(String oldJarName, String version) throws NullPointerException {


        String[] split = oldJarName.split("\\.");
        return oldJarName.split("\\.")[0] + "-" + version + "." + split[1];

    }


}
